
package cn.benma666.kettle.mytuils;

import cn.benma666.constants.UtilConst;
import cn.benma666.iframe.DictManager;
import cn.benma666.iframe.Result;
import cn.benma666.kettle.domain.VJob;
import cn.benma666.myutils.StringUtil;
import cn.benma666.sjzt.Db;
import com.alibaba.fastjson.JSONObject;
import org.beetl.sql.core.SqlId;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.job.entries.special.JobEntrySpecial;

import java.util.List;

/**
* 任务定时 <br/>
* date: 2016年5月24日 <br/>
* @author jingma
* @version 0.1
*/
public class TimingUtil{

	/**
	* 将定时对象转为简单可理解的文本 <br/>
	* @author jingma
	* @param timing 定时对象
	*/
	public static String showText(JSONObject timing){
        //是否重复
        String isRepeat = timing.getString("repeat");
        String initSatrt = timing.getString("initStart");
        //定时类别
        int schedulerType = timing.getIntValue("schedulerType");
        int hour = timing.getIntValue("hour");
        int minutes = timing.getIntValue("minutes");
        String result = "";
        if(JobEntrySpecial.NOSCHEDULING==schedulerType){
            result = "不需要定时";
        }else if(JobEntrySpecial.INTERVAL==schedulerType){
            int intervalSeconds = timing.getIntValue("intervalSeconds");
            int intervalMinutes = timing.getIntValue("intervalMinutes");
            if(intervalMinutes==0){
                result = "等"+intervalSeconds+"秒";
            }else{
                result = "等"+intervalMinutes+"分"+intervalSeconds+"秒";
            }
        }else if(JobEntrySpecial.DAILY==schedulerType){
            result = "一天的"+hour+"点"+minutes+"分";
        }else if(JobEntrySpecial.WEEKLY==schedulerType){
            int weekDay = timing.getIntValue("weekDay");
            String week = DictManager.zdMcByDm(UtilConst.DICT_SYS_COMMON_XQ, Integer.toString(weekDay));
            result = week + "的"+hour+"点"+minutes+"分";
        }else if(JobEntrySpecial.MONTHLY==schedulerType){
            int dayOfMonth = timing.getIntValue("dayOfMonth");
            result = "一个月的"+dayOfMonth+"日"+hour+"点"+minutes+"分";
        }else if(JobEntrySpecial.CRON==schedulerType){
            result = timing.getString("cron");
        }
        if(UtilConst.WHETHER_TRUE.equals(isRepeat)){
            result+="/重";
        }
        if(UtilConst.WHETHER_TRUE.equals(initSatrt)){
            result+="/初";
        }
        return result;
	}
	/**
	* 根据作业id得到定时配置的字符串描述 <br/>
	* @author jingma
	*/
	public static String showTextByJobid(VJob job) {
	    return showText(getTimingByJobId(job));
	}

    /**
    * 通过作业ID获取作业定时信息<br/>
    * @author jingma
    * @param job 作业
    * @return SATRT控件实体
    */
    public static JSONObject getTimingByJobId(VJob job) {
        Integer startId = getStartIdByJobId(job);
        List<JSONObject> records = Db.use(job.getZyk()).find(SqlId.of("kee",
                        "selectZydscs"), Db.buildMap(startId));
        JSONObject result = new JSONObject();
        for(JSONObject record:records){
            if(StringUtil.isNotBlank(record.getString("value_str"))){
                result.put(record.getString("code"), record.getString("value_str"));
            }else{
                result.put(record.getString("code"), record.getIntValue("value_num"));
            }
        }
        String cron = result.getString("cron");
        if(StringUtil.isBlank(cron)||UtilConst.WHETHER_FALSE.equals(cron)){
            //设置个默认值
            result.put("cron","0 0 * * * ? *");
        }
        //转为字符串类型
        result.put("schedulerType", result.getString("schedulerType"));
        result.put("weekDay", result.getString("weekDay"));
        result.put("repeat", StringUtil.whether(result.getString("repeat")));
        result.put("initStart", StringUtil.whether(StringUtil.valByDef(result.getString("initStart"),UtilConst.WHETHER_FALSE)));
        return result;
    }

    /**
    * 根据作业id获取该作业的开始控件id <br/>
    * @author jingma
    */
    public static Integer getStartIdByJobId(VJob job) {
        //START控件的类型编号是74，每个JOB只有一个START控件，所有可以唯一确定
        JSONObject startIdObj = Db.use(job.getZyk()).findFirst(SqlId.of("kee",
                        "selectZykskjid"), Db.buildMap(job.getId_job(),
                KettleManager.getJobentryTypeId(job,"SPECIAL")));
        return StringUtil.requireNonNull(startIdObj,"没有找到作业的开始控件").getIntValue("id_jobentry");
    }
    /**
    * 保存定时到kettle的表中方式 <br/>
    * 直接修改相关表数据，效率高，存在风险<br/>
    * @author jingma
    */
    public static Result saveTimingToKettle(VJob job, JSONObject timing) throws KettleException {
        Integer startId = getStartIdByJobId(job);
        String sql = "update r_jobentry_attribute ja "
                + "set ja.VALUE_NUM=?,ja.VALUE_STR=? "
                + "where ja.id_jobentry="+startId
                + " and ja.code=?";
        for(String key:new String[]{"repeat","initStart"}){
            if(StringUtil.isNotBlank(timing.getString(key))){
                Db.use(job.getZyk()).update(sql, 0,UtilConst.WHETHER_TRUE.equals(
                        timing.getString(key))?"Y":"N",key);
            }
        }
        for(String key:new String[]{"schedulerType","intervalSeconds","intervalMinutes",
                "hour","minutes","weekDay","dayOfMonth"}){
            if(StringUtil.isNotBlank(timing.getString(key))){
                Db.use(job.getZyk()).update(sql, timing.getIntValue(key), null,key);
            }
        }
        if(StringUtil.isNotBlank(timing.getString("cron"))){
            Db.use(job.getZyk()).update(sql,0, timing.getString("cron"), "cron");
        }
        VJob njob = new VJob(job.getZyk(),job.getId_job());
        njob.setDsms(showText(getTimingByJobId(job)));
        return KettleManager.updateZykz(njob);
    }
}
